/**
 *  选区模型
 *  记录当前的选区内容
 */
import EventEmitter from "events";
import type { TextModel } from "./text_model"

export interface Selection {
    anchor: number
    focus: number
}

export class SelectionModel extends EventEmitter {
    private textModel_?: TextModel;
    private selection_: Selection = { anchor: 0, focus: 0 };
    constructor(textModel: TextModel) {
        super()
        this.textModel_ = textModel
        // this.selection_ = { anchor: 0, focus: 0 } //光标的位置
    }


    getSelection() {
        return { ...this.selection_ } //展开是为了防止外部有更改
    }
    setSelection(selection: Selection) {
        if (selection && this.selection_ && selection.anchor === this.selection_.anchor && selection.focus === this.selection_.focus) {
            return
        }
        this.selection_ = { ...selection }
    }
    // 光标是否重合
    isCollapsed() {
        return this.selection_ && this.selection_.anchor === this.selection_.focus
    }
    // 开始位置大于结束位置是否
    isBackward() {
        return this.selection_ && this.selection_.anchor > this.selection_.focus
    }

    isEnd() {
        return !this.textModel_
            ?.getSpacers()
        [this.selection_.anchor + 1]?.replace(/\s\S/, "")
    }
}

export default SelectionModel